﻿namespace EyeOpen.Market.ViewModel
{
    using System.Collections.ObjectModel;
    using System.ComponentModel;
    using System.Windows.Input;
    using EyeOpen.Commerce.Domain;
    using EyeOpen.Markert.Client.BootStrapper;
    using EyeOpen.Market.Client.Service;
    using EyeOpen.UI.Silverlight;

    public class CustomerViewModel : INotifyPropertyChanged
    {
        private readonly IMarketServiceAsynchronous marketServiceAsynchronous =
            new MarkertServiceAsynchronousFactory()
            .CreateServiceContext();

        private bool isBusy;

        public CustomerViewModel()
        {
            LoadCustomerCollectionCommand = new RelayCommand(PerformLoadCustomerCollection);
            CustomerCollection = new ObservableCollection<Customer>();
            marketServiceAsynchronous.CustomerListLoaded += MarketServiceAsynchronousCustomerListLoaded;
        }

        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// Returns true if the application is busy with loading customers.
        /// </summary>
        public bool IsBusy
        {
            get
            {
                return isBusy;
            }

            set
            {
                isBusy = value;
                OnPropertyChanged("IsBusy");
            }
        }

        public ObservableCollection<Customer> CustomerCollection
        {
            get;
            set;
        }

        public ICommand LoadCustomerCollectionCommand
        {
            get;
            private set;
        }

        public void PerformLoadCustomerCollection()
        {
            IsBusy = true;
            marketServiceAsynchronous.GetAllCustomer();
        }

        protected virtual void OnPropertyChanged(string propertyName)
        {
            var handler = PropertyChanged;

            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        private void MarketServiceAsynchronousCustomerListLoaded(object sender, CustomerListEventArgs e)
        {
            CustomerCollection.Clear();

            foreach (var customer in e.Result)
            {
                CustomerCollection.Add(customer);
            }

            IsBusy = false;
        }
    }
}
